﻿using DocTranslator.Services.Interfaces;
using NPOI.HPSF;
using NPOI.XWPF.UserModel;
using System.IO;

namespace DocTranslator.Services
{
    public class WordDocumentService : IWordDocumentService
    {
        private readonly ILogger<WordDocumentService> _logger;

        public WordDocumentService(ILogger<WordDocumentService> logger)
        {
            _logger = logger;
        }

        // 处理单个文档
        public async Task<string> ProcessDocumentAsync(string filePath, ITranslationService translationService, Action<int, int> progressCallback = null, string outputDirectory= null)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException($"文件不存在: {filePath}");
 
            try
            {
                // 读Word文档
                using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    XWPFDocument doc = new XWPFDocument(fileStream);
                    // 计算总元素数量（段落 + 表格单元格）
                    int totalElements = CountElements(doc);
                    int processedElements = 0;

                    // 处理所有段落
                    foreach (var paragraph in doc.Paragraphs)
                    {
                        string text = paragraph.Text;
                        if (!string.IsNullOrWhiteSpace(text))
                        {
                            string translatedText = await translationService.TranslateAsync(text);
                            if (!string.IsNullOrWhiteSpace(translatedText))
                            {
                                paragraph.ReplaceText(text, translatedText);
                            }
                        }

                        processedElements++;
                        // 更新进度
                        progressCallback?.Invoke(processedElements, totalElements);
                    }

                    // 处理表格中的文本
                    foreach (var table in doc.Tables)
                    {
                        foreach (var row in table.Rows)
                        {
                            foreach (var cell in row.GetTableCells())
                            {
                                foreach (var paragraph in cell.Paragraphs)
                                {
                                    string text = paragraph.Text;
                                    if (!string.IsNullOrWhiteSpace(text))
                                    {
                                        string translatedText = await translationService.TranslateAsync(text);
                                        if (!string.IsNullOrWhiteSpace(translatedText))
                                        {
                                            paragraph.ReplaceText(text, translatedText);
                                        }
                                    }

                                    processedElements++;
                                    progressCallback?.Invoke(processedElements, totalElements);
                                }
                            }
                        }
                    }

                    // 生成翻译后的文件路径并保存
                    //string translatedFilePath = GenerateTranslatedFilePath(filePath, outputDirectory);
                    //string translatedFilePath = Path.Combine(outputDirectory, $"{Path.GetFileName(filePath)}_translatedEnglish");

                    string fileNameWithoutExt = Path.GetFileNameWithoutExtension(filePath);
                    string extension = Path.GetExtension(filePath);
                    string translatedFilePath = Path.Combine(outputDirectory, $"{fileNameWithoutExt}_translatedEnglish{extension}");
                    using (var outputStream = new FileStream(translatedFilePath, FileMode.Create))
                    {
                        doc.Write(outputStream);
                    }

                    return translatedFilePath;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理文档时发生错误: {filePath}");
                throw;
            }
        }


        // 处理多个文档
        public async Task<List<string>> ProcessDocumentsAsync(List<string> filePaths, ITranslationService translationService, Action<int, int, int, int, string> progressCallback = null, string outputDirectory = null)
        {
            var resultFiles = new List<string>();
            int totalFiles = filePaths.Count;
            int processedFiles = 0;

            // 总元素数
            int grandTotal = 0;
            foreach (var filePath in filePaths)
            {
                using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                var doc = new XWPFDocument(fs);
                grandTotal += CountElements(doc);
            }

            // 已处理元素数
            int grandProcessed = 0; 
            foreach (var filePath in filePaths)
            {
                try
                {
                    string fileName = Path.GetFileName(filePath);
                    progressCallback?.Invoke(processedFiles, totalFiles, grandProcessed, grandTotal, $"处理中: {fileName}");

                    string translatedFilePath = await ProcessDocumentAsync(
                        filePath,
                        translationService,
                        (processed, total) =>
                        {
                            grandProcessed++;
                            progressCallback?.Invoke(processedFiles, totalFiles, grandProcessed, grandTotal,
                                $"处理中: {fileName} ({processed}/{total})");
                        },
                        outputDirectory);

                    resultFiles.Add(translatedFilePath);
                    processedFiles++;

                    progressCallback?.Invoke( processedFiles, totalFiles, grandProcessed, grandTotal, $"已完成: {fileName}");


                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"处理文档失败: {filePath}");
                    processedFiles++;
                    progressCallback?.Invoke(processedFiles, totalFiles, processedFiles, totalFiles, $"处理失败: {Path.GetFileName(filePath)}");
                }
            }

            return resultFiles;
        }


        private int CountElements(XWPFDocument doc)
        {
            // 计算段落数量
            int count = doc.Paragraphs.Count;

            foreach (var table in doc.Tables)
            {
                foreach (var row in table.Rows)
                {
                    foreach (var cell in row.GetTableCells())
                    {
                        count += cell.Paragraphs.Count;
                    }
                }
            }

            return count;
        }


    }
}
